{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# gtburst\n",
    "\n",
    "This tutorial provides a step-by-step guide to using the **gtburst** GUI for GRB and solar flare analysis of GBM and LAT data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What it is used for?\n",
    "\n",
    "Gtburst can be used to do the following:\n",
    "* GBM data:\n",
    "    * download data from the GBM Trigger catalog, select data analysis interval, and interactively fit the background\n",
    "    * write out pha and rsp files for spectral analysis in either XSPEC or RMFIT\n",
    "\n",
    "* LLE data:\n",
    "    * download data from the Fermi LAT Low-Energy Events Catalog, select data analysis interval, and interactively fit the background\n",
    "    * write out pha and rsp files for spectral analysis in either XSPEC or RMFIT\n",
    "\n",
    "* LAT data:\n",
    "    * download photon events and spacecraft data from the LAT Data server\n",
    "    * produce navigation plots to allow user to select optimal time intervals and zenith cuts\n",
    "    * do photon selections based on energy, Region Of Interest (ROI), time, zenith, event class\n",
    "    * produce counts maps\n",
    "    * do likelihood analysis given a simple spectral model and background models\n",
    "    * localization using **gtfindsrc** or a TS map\n",
    "    * writes out pha and rsp files for spectral analysis in either XSPEC or RMFIT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prerequisites:\n",
    "\n",
    "* Internet connection\n",
    "* Recent version of **gtburst**\n",
    "* Latest installation of the Fermitools"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Updating gtburst \n",
    "\n",
    "Before starting this analysis thread, make sure you have the latest version of **gtburst**. **gtburst** adopts a \"release early, release often\" model, thus it is a good habit to check often for updates. **gtburst** can be easily updated via the Update functionality. `Menu: Update -> Update` to the latest version.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image01.png'>\n",
    "\n",
    "This syncs with the [github repository](https://github.com/giacomov/gtburst). You may need to sync twice initially to get to the latest version. After each update, you'll need to restart gtburst, which is automatically prompted."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Immediate help from the interface\n",
    "\n",
    "* At any step in any analysis task, you can read in the lower left corner a description on what you are supposed to do and some hints about things to keep in mind.\n",
    "\n",
    "* If you don't remember what a given parameter in a command means, you can always click on the question mark \"?\" on the right of the parameter to get a short description of its meaning."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Analysis of a Gamma-Ray Burst\n",
    "\n",
    "For this thread, we will analyze GRB080916C, one of the brightest LAT GRBs on record. All outputs from GUI window are in `gtburst.log`.\n",
    "\n",
    "Steps:\n",
    "\n",
    "1. To start using **gtburst** for any analysis\n",
    "    * Open a terminal, and cd into a directory where you wish the gtburst output files to go. You may wish to make a sub directory specific to the object being analyzed to keep files organized (e.g. GRB080916C).\n",
    "    * Type **gtburst** at command line.\n",
    "\n",
    "\n",
    "2. Downloading data\n",
    "\n",
    "    **gtburst** can download GBM, LLE, and LAT data from the FSSC, can be run on datasets previously downloaded, or can be loaded as a custom dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gtburst"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image02.png'>\n",
    "\n",
    "Download datasets ...\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image03.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The trigger details can either be entered manually, or retrieved from the trigger catalog which includes both Swift-BAT and Fermi-GBM triggers.\n",
    "\n",
    "Click `Browse triggers`\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image04.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Triggers can be sorted by any of the columns by clicking on the header, or filtered by trigger type.\n",
    "\n",
    "Note: GBM triggers may not appear immediately in this database, as they depend on the GBM team populating the table, which is done within 48 hours of the trigger.\n",
    "\n",
    "Select the trigger and click `Done` (bn080916009 for GRB 080916C in this example).\n",
    "\n",
    "A box will pop up to confirm data selection. Time Tagged Events (TTE) versus binned CTIME data. TTE data files have finer time resolution and are therefore larger, and can be binned as needed.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image05.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3. GBM & LLE Data Analysis\n",
    "\n",
    "    * A box will pop up to select the datasets for the following analysis. The number of degrees in parentheses is the angle from the individual detector boresight to the GRB. By default, the 3 or 4 smallest angle NaI's, the 1 smallest angle BGO, and LAT & LLE data will be selected. The backgrounds will be fit and spectral files created for only the selected detectors. The user may select additional detectors.\n",
    "    \n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image06.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Make spectra for XSPEC - will walk user through background and source selection, and output rsp & pha files.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image08.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* By default, the user will click to select the time intervals for source and background selection. The source interval will be chosen only once for the first detector used, which is the smallest angle NaI by default (n3 in this example).\n",
    "\n",
    "    Click `Run` to select interactively.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image09.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Zoom into the GRB emission using the <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image10.png'> button, and drawing a box around the GRB emission. Click the button again to exit the zoom feature.\n",
    "\n",
    "    At any time, click <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image11.png'> to zoom back out. You can repeatedly refine the box smaller.\n",
    "\n",
    "    Once zoomed sufficiently, click once at the beginning of the interval, and again at the end. Once you are happy with the selection, click `Done`.\n",
    "    \n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image12.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Background fitting - click next, and then `Run` to interactively fit the background. Now zoom in to a region around the burst emission to fit the background. A few hundred seconds or so before and after the burst is usually sufficient. Select one interval prior to the burst (by clicking at the beginning and end) and another interval after the burst, where the background is approximately flat. Then click `Done`.\n",
    "\n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image13.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* An automated fit to the background, which fits various polynomials is performed, to find the best fit. A plot showing the background-subtracted light curve is produced. If you are happy with the result, click `OK`, otherwise `Retry` to select new background intervals.\n",
    "\n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image14.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* You will now need to produce a background fit for each subsequent detector. The same source interval is assumed. Redo e-f for each detector including BGO & LLE.\n",
    "\n",
    "* When all detectors are completed, click Next, and then Run to produce the output files, and Finish to go back to the starting menu. The directory where you're running gtburst should now contain the following files, which can be read into XSPEC to conduct a joint spectral fit as described in http://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/combined_LAT_GBM.html\n",
    "```\n",
    "bn080916009_n3_srcspectra.pha\n",
    "bn080916009_n3_weightedrsp.rsp\n",
    "bn080916009_n3_bkgspectra.bak\n",
    "bn080916009_n4_srcspectra.pha\n",
    "bn080916009_n4_weightedrsp.rsp\n",
    "bn080916009_n4_bkgspectra.bak\n",
    "bn080916009_n6_srcspectra.pha\n",
    "bn080916009_n6_weightedrsp.rsp\n",
    "bn080916009_n6_bkgspectra.bak\n",
    "bn080916009_b0_srcspectra.pha\n",
    "bn080916009_b0_weightedrsp.rsp\n",
    "bn080916009_b0_bkgspectra.bak\n",
    "bn080916009_LAT-LLE_srcspectra.pha\n",
    "bn080916009_LAT-LLE_weightedrsp.rsp\n",
    "bn080916009_LAT-LLE_bkgspectra.bak\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4. LAT Data Analysis\n",
    "    * After downloading a dataset or loading data from a directory, it's best to start with the navigation plot.\n",
    "    \n",
    "    Click Tools->Make navigation plots\n",
    "\n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image15.png'>\n",
    "    \n",
    "    The navigation plots will pop up in a separate window. The upper plot is the angle between the GRB RA/Dec and the Fermi zenith angle. This indicates when the GRB is and is not occulted by the Earth. A zenith angle cut of 100 is fairly standard for a GRB, but can be adjusted slightly higher if the source is very bright at that time, or lower if the source is fainter and the user is concerned about Earth limb contamination.\n",
    "    \n",
    "    The lower panel of the navigation plot is the angle between the GRB RA/Dec and the boresight of the LAT. This indicates when the source is within the LAT FoV. The size of the LAT FoV is dependent on energy and event class.\n",
    "    \n",
    "    The navigation plots are in reference to the GRB localization in the GBM GRB catalog, which may be the best available GBM position (~few deg), an announced LAT position (~0.1-1 deg), or a much more accurate position from follow-up (~arcsec). The user can manually adjust the position in the GUI window at this time, or later based upon the counts map. If the user changes the R.A. and Dec. in the initial window, making the navigation plots again will update the plots using the new position.\n",
    "    \n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image16.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "***"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Likelihood Analysis\n",
    "\n",
    "    Click `Tasks->Make likelihood analysis`\n",
    "\n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image17.png'>\n",
    "    <img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image18.png'>\n",
    "\n",
    "    The first step is filtering for the counts map, which can be repeated and optimized. The parameters:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "rad - radius of interest (degrees). Customary values corresponds to the 95% containment of the PSF at the emin energy. If you use `emin=100` MeV, rad should be 12 deg for any Transient class and 10 deg for Source or cleaner classes.\n",
    "\n",
    "irf - the event class - in GRB analysis transient class is usually sufficient for short (<100 s) timescales and spectral analysis, and source class is better for longer intervals and localizations. Event Class recommendations for different analyses are discussed at: http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Data/LAT_DP.html\n",
    "\n",
    "zmax - Zenith angle cut. If the parameter `strategy=time` (default), any time interval where any part of the ROI is at a Zenith angle larger than zmax is excluded. This is the normal choice for GRB and SF analysis. If `strategy=events`, all events with a Zenith angle larger than zmax will be excluded. The user is strongly advised against using `strategy=events`, unless he/she understands exactly its implication, since such choice can introduce systematic uncertainties in the analysis difficult to estimate.\n",
    "\n",
    "Tstart - time to start analysis relative to GRB trigger. This can be specified either as a time from the trigger time, or as a Mission Elapsed Time (MET). The interface will automatically understand, since MET numbers are very big.\n",
    "\n",
    "Tstop - time to stop analysis relative to GRB trigger. This can be specified either as a time from the trigger time, or as a Mission Elapsed Time (MET). The interface will automatically understand, since MET numbers are very big.\n",
    "\n",
    "Emin - minimum energy for analysis in MeV. Normal value is 100 MeV, as going below that requires special attention.\n",
    "\n",
    "Emax - maximum energy for analysis in MeV\n",
    "\n",
    "Skybinsize - binning for map\n",
    "\n",
    "Thetamax - This is an additional cut which will exclude from the analysis time intervals in which the position of the source is at more than Thetamax degrees from the center of the LAT field of view. Since the PSF of the LAT becomes worse and more uncertain at high off-axis angles, this can be used when analyzing bright bursts to reduce the errors on the localization. It is usually not necessary to change this value.\n",
    "\n",
    "Strategy - method of zenith angle cut"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using `strategy=time` (the standard value) will exclude from the analysis all time intervals in which any part of the ROI is at Zenith angles larger than the zmax value.\n",
    "\n",
    "Do not change this value unless you know what you are doing! Using `strategy=events` will exclude from the analysis all events with a Zenith angle larger than zmax, which can introduce subtle systematic errors in the analysis difficult to judge.\n",
    "\n",
    "Click `Run`:\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image19.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You will then see the resulting counts map and photon energy as a function of time.\n",
    "\n",
    "You can click on photons on the right plot, which will be highlighted on the left plot with a small white circle. This is helpful for determining if a particular high energy photon is clustered near others. A small text box will also appear with the ID of the run in which the event was detected, the event ID, the Zenith and the off-axis (theta) angle of that event.\n",
    "\n",
    "You can also zoom in the left plot, and only the photons within your zoomed area will remain in the right plot. This is useful for example to figure out which photons are close to the source position. Note that if you zoom in the right plot, the left plot will NOT change since this would require a new run of the command.\n",
    "\n",
    "Click `Next`:\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image20.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we choose the components of our likelihood model. This command will produce a XML file containing your likelihood model, as described here ([link_to_likelihood_tutorial]). For source class, a particle model of isotr template is appropriate. The other defaults are sufficient. Click `Run`; once that finishes, click `Next`.\n",
    "\n",
    "Gtburst will automatically add nearby bright catalog sources to your XML file. Once the dialog box finishes, click `Run`.\n",
    "\n",
    "A window summarizing the fit parameters of the model will pop up. You can modify the parameters (e.g. fixing index to some value), or simply click `Done` to leave everything as it is.\n",
    "\n",
    "If you make changes, be sure to click `Save`, and click `Done` when finished. Then, once the window with the list of parameters is closed, click `Next`.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image21.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you will be given options on the outputs of the likelihood analysis.\n",
    "\n",
    "`Optimizeposition=yes` will call **gtfindsrc** at the end of the likelihood analysis and attempt to improve the GRB localization.\n",
    "\n",
    "`Showmodelimage=yes` will create a model map and display it. This does not have any impact on the actual analysis, but allow you to see a representation of your final model.\n",
    "\n",
    "`Spectralfiles=yes` will create the pha and rsp files necessary to do spectral analysis in XSPEC or rmfit.\n",
    "\n",
    "Each of these steps will make the analysis take longer. Click `Run`.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image22.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Results:\n",
    "\n",
    "Likelihood fit result parameters of GRB, relevant nearby sources, and background models. You must close this window to proceed.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image23.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Resulting count map and likelihood model image. GRB 080916C is well detected!\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image24.png'>\n",
    "\n",
    "If a substantially improved position is available, enter this position in the start window, which can be reached by clicking Finish, then repeat likelihood analysis from that position."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "***"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* TS map - If photon clustering isn't entirely obvious or to potentially improve the localization further, one can create a TS map, which can take a while to run, especially on a long dataset. For very bright GRBs, note that the binning may be more of a limiting factor then the photon statistics on localization determination.\n",
    "\n",
    "    `Tasks->Find source` in TS Map\n",
    "    \n",
    "    Follow similar steps as the likelihood analysis, ending up with a map and localization. For GRB 080916C, the localization is not improved by the TS map because the statistical error is smaller than the TS map binsize."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/gtburst/image25.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Choose new center for likelihood analysis, useful for localizing a GBM burst, based upon visual determination of the position of the cluster of photons in the counts map.\n",
    "\n",
    "    Tasks -> Interactively recenter ROI\n",
    "\n",
    "    Make photon selections, click `Run`. Once it finishes, click `Next`, and `Run`.\n",
    "\n",
    "    Click on a new center position on the left counts map. Click `Run`, and finish. Then repeat the likelihood analysis step at this new location."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
